package hu.mapro.gwtui.gxt.client.fieldseditor.field;

import hu.mapro.model.Getter;
import hu.mapro.model.Setter;
import hu.mapro.model.meta.Field;
import hu.mapro.model.meta.HasLabel;

import com.google.gwt.editor.client.EditorDelegate;
import com.google.gwt.user.client.ui.Widget;

public final class EditorFieldAdapter<T, V, F extends Field&HasLabel&Getter<T, ?>&Setter<T, ?>> implements
		hu.mapro.gwtui.gxt.client.fieldseditor.EditorFieldInterface<T, V> {
	private final EditorFieldInterface<V> delegate;
	private final F field;

	public EditorFieldAdapter(EditorFieldInterface<V> delegate, F field) {
		assert delegate != null;
		this.delegate = delegate;
		this.field = field;
	}

	@Override
	public void setContext(
			hu.mapro.gwtui.gxt.client.fieldseditor.FieldCreationInterface ctx) {
		delegate.setContext(ctx);
	}

	@Override
	public void flush() {
		delegate.flush();
	}

	@Override
	public void setDelegate(EditorDelegate<V> d) {
		delegate.setDelegate(d);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	class Accessor implements Getter, Setter {

		@Override
		public void set(Object object, Object value) {
			((Setter)field).set(object, value);
		}

		@Override
		public Object get(Object object) {
			return ((Getter)field).get(object);
		}
		
	}

	Accessor accessor = new Accessor();
	
	@SuppressWarnings("unchecked")
	@Override
	public  void edit(T baseObject) {
		delegate.edit(accessor, baseObject);
	}

	@Override
	public Widget asWidget() {
		return delegate.asWidget();
	}

	@Override
	public void focus() {
		delegate.focus();
	}

	@Override
	public void checkDirty() {
		delegate.checkDirty();
	}

	@Override
	public String getPropertyName() {
		return field.getName();
	}

	@Override
	public String getLabel() {
		return field.getLabel();
	}

	@SuppressWarnings("unchecked")
	@Override
	public V getValue(T object) {
		return (V) field.get(object);
	}
}